import type { PreviewData } from '@/stores/exposureLine.ts'

/**
 * 精确到小数位
 */
export const accurateToFixed = (num: number, decimalPlaces: number) => {
  // 处理非数字输入
  if (isNaN(num)) return NaN.toString()

  // 处理小数位数为0的情况
  if (decimalPlaces <= 0) return Math.round(num).toString()

  // 使用科学计数法避免浮点精度问题
  const factor = Math.pow(10, decimalPlaces)
  const rounded = Math.round((num + Number.EPSILON) * factor) / factor

  // 转换为字符串处理
  let str = rounded.toString()

  // 处理科学计数法
  if (str.indexOf('e') !== -1) {
    return rounded.toFixed(decimalPlaces)
  }

  // 确保有小数点
  if (str.indexOf('.') === -1) {
    str += '.'
  }

  // 补全小数位数
  const decimalIndex = str.indexOf('.')
  const existingDecimals = str.length - decimalIndex - 1

  if (existingDecimals < decimalPlaces) {
    str += '0'.repeat(decimalPlaces - existingDecimals)
  } else if (existingDecimals > decimalPlaces) {
    str = str.substring(0, decimalIndex + decimalPlaces + 1)
  }

  return str
}

/**
 * startDate，endDate长度一致化处理
 */
export const completeEndDates = (startDate: string[], endDate: string[]): string[][] => {
  if (endDate.length === startDate.length) {
    return [startDate, endDate]
  }
  if (startDate.length > endDate.length) {
    const date = endDate[0].slice(0, 10)
    startDate.forEach((currentDate, i) => {
      if (!endDate[i]) {
        endDate[i] = date + currentDate.slice(-9)
      }
    })
  } else {
    const date = startDate[0].slice(0, 10)
    endDate.forEach((currentDate, i) => {
      if (!startDate[i]) {
        startDate[i] = date + currentDate.slice(-9)
      }
    })
  }
  return [startDate, endDate]
}

/**
 * 填充时间序列数据
 */
export const fillTimeSeriesData = (originalData: PreviewData[], granularity = 2) => {
  if (granularity === 1) return originalData
  const step = granularity === 2 ? 5 : 60 // 每步分钟数
  const result = []
  const sampleItem = originalData[0]
  const fields = Object.keys(sampleItem).filter(key => key !== 'date')

  // 获取日期字符串（只保留 yyyy-MM-dd）
  const targetDateStr = originalData[0].date.slice(0, 10) // '2025-07-17'

  // 创建起止时间，使用本地时间（年、月、日）
  const [year, month, day] = targetDateStr.split('-').map(Number)
  const start = new Date(year, month - 1, day, 0, 0, 0) // 本地时间
  const end = new Date(year, month - 1, day, 23, 59, 59)

  // 构建 Map 用于查找原始数据
  const dataMap = new Map()
  originalData.forEach(item => {
    dataMap.set(item.date, item)
  })

  // 构造时间序列
  for (let d = new Date(start); d <= end; d.setMinutes(d.getMinutes() + step)) {
    const yyyy = d.getFullYear()
    const MM = String(d.getMonth() + 1).padStart(2, '0')
    const dd = String(d.getDate()).padStart(2, '0')
    const HH = String(d.getHours()).padStart(2, '0')
    const mm = String(d.getMinutes()).padStart(2, '0')
    const dateTime = `${yyyy}-${MM}-${dd} ${HH}:${mm}:00`

    const existing = dataMap.get(dateTime)
    if (existing) {
      result.push(existing)
    } else {
      const newItem = { date: dateTime } as any
      fields.forEach(field => {
        newItem[field as keyof PreviewData] = 0
      })
      result.push(newItem)
    }
  }

  return result
}
